package client

import (
	"cloud_worm/util/uhttp"
	"github.com/golang/glog"
	"time"
	"encoding/json"
	"fmt"
	"cloud_worm/util/proto/ujson"
)

func InitConfig(a *Agent) error {
	var respContent string
	for {
		respContent = uhttp.HttpsGet(fmt.Sprintf("%s?version=%d", a.SrvConfigUrl, a.Version))
		if respContent == "" {
			// 请求超时，一直请求中
			glog.Errorf("fail to get config.json for '%d', go to retry~", a.Version)
			time.Sleep(a.HttpIntervalTime * time.Second)
		} else {
			// 请求内容存在
			break
		}
	}

	// 所有配置的节点的键值
	var response uhttp.ResponData
	if err := json.Unmarshal([]byte(respContent), &response); err != nil {
		return fmt.Errorf("parse config data '%s?version=%d' failed: %s", a.SrvConfigUrl, a.Version, err.Error())
	}
	if response.Code != uhttp.RespCodeOk {
		return fmt.Errorf("parse config data '%s?version=%d failed: %d", a.SrvConfigUrl, a.Version, response.Code)
	}
	glog.Info(response.Data)

	var config ujson.AgentRouteConfig
	if err := uhttp.MapDecode(response.Data, &config); err != nil {
		return fmt.Errorf("mapstruct decode failed: %s", err.Error())
	}
	glog.Info("%#v", config)

	var err error
	if config.ConfigUrl != a.SrvConfigUrl {
		a.SrvConfigUrl = config.ConfigUrl
		err = InitConfig(a)
	}

	if err == nil {
		a.SrvConfigUrl = config.ConfigUrl
		a.ServerAddr = config.SocketAddress
		a.IntervalTime = time.Duration(config.Timeout)
		a.HeartBeatTimeout = time.Duration(config.HeartbeatTimeout)
	}

	return err
}
